package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.util.SMSUtils;
import com.itheima.reggie.util.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired(required = false)
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){

        //1.获取手机号
        String phone = user.getPhone();
        //2.生成4位数的验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        //3.调用阿里的工具类去发送短信
        //SMSUtils.sendMessage("黑马旅游网","SMS_198917972",phone,code);
        System.out.println("本次验证码:"+code);
//        //4.把验证码存储到session中
//        session.setAttribute(phone,code);
        //把验证码存入缓存中
        redisTemplate.opsForValue().set(phone,code,300, TimeUnit.SECONDS);
        //5.返回信息
        return R.success("发送成功");
    }

    @RequestMapping("/login")
    public R<User> login(@RequestBody Map<String, String> map,HttpSession session){
        //1.取出参数
        String phone = map.get("phone");
        String code = map.get("code");
        String codeInSession = (String) redisTemplate.opsForValue().get(phone);
        //2.把参数交给业务层,返回当前登陆者对象
        User user = userService.login(phone,code,codeInSession);
        //判断
        if (user!=null){
            redisTemplate.delete(phone);
            session.setAttribute("user",user.getId());
           // session.removeAttribute(phone);
        }else {
            return R.error("登录失败");
        }
        //返回响应
        return R.success(user);
    }

    //退出登录
    @RequestMapping("/loginout")
    public R<String> logout(HttpSession session) throws IOException {
        session.invalidate();
        return R.success("退出成功");
    }
}
